<%@ page language="java" import="java.util.*" pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    String webSocketPath = request.getServerName() + ":" + request.getServerPort() + path;
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
    <meta charset="UTF-8">
    <title>WebVR模型页面</title>
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0, shrink-to-fit=no">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

    <script>
        WebVRConfig = {
            /**
             * webvr-polyfill configuration
             */

            // Forces availability of VR mode.
            //FORCE_ENABLE_VR: true, // Default: false.

            // Complementary filter coefficient. 0 for accelerometer, 1 for gyro.
            //互补滤波系数。加速度计在静止的时候是很准的，但运动时的角度噪声很大，陀螺仪反之。
            //互补滤波器徘徊在信任陀螺仪和加速度计的边界。首先选择一个时间常数，然后用它来计算滤波器系数。
            //例如陀螺仪的漂移是每秒2度，则可能需要一个少于一秒的时间常数去保证在每一个方向上的漂移不会超过2度。
            //但是当时间常数越低，越多加速度计的噪声将允许通过。所以这是一个权衡的内容。
            //K_FILTER: 0.98, // Default: 0.98.

            // How far into the future to predict during fast motion.
            //由于有给定的方向以及陀螺仪信息，选择允许预测多长时间之内的设备方向，在设备快速移动的情况下可以让渲染比较流畅。
            //PREDICTION_TIME_S: 0.040, // Default: 0.040 (in seconds).

            // Flag to disable touch panner. In case you have your own touch controls
            //TOUCH_PANNER_DISABLED: true, // Default: false.

            // Enable yaw panning only, disabling roll and pitch. This can be useful for
            // panoramas with nothing interesting above or below.
            // 仅关心左右角度变化，忽略上下和倾斜等。
            // YAW_ONLY: true, // Default: false.

            // Enable the deprecated version of the API (navigator.getVRDevices).
            //ENABLE_DEPRECATED_API: true, // Default: false.

            // Scales the recommended buffer size reported by WebVR, which can improve
            // performance. Making this very small can lower the effective resolution of
            // your scene.
            //在VR显示模式下对WebVR推荐的屏幕比例进行缩放。在IOS下如果不为0.5会出现显示问题，查看
            //https://github.com/borismus/webvr-polyfill/pull/106
            BUFFER_SCALE: 0.5, // default: 1.0

            // Allow VRDisplay.submitFrame to change gl bindings, which is more
            // efficient if the application code will re-bind it's resources on the
            // next frame anyway.
            // Dirty bindings include: gl.FRAMEBUFFER_BINDING, gl.CURRENT_PROGRAM,
            // gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING,
            // and gl.TEXTURE_BINDING_2D for texture unit 0
            // Warning: enabling this might lead to rendering issues.
            //允许 VRDisplay.submitFrame使用脏矩形渲染。但是开启此特性可能会出现渲染问题。
            //DIRTY_SUBMIT_FRAME_BINDINGS: true // default: false
        };
    </script>


    <%--<script type="text/javascript" src="jquery/jquery-easyui-1.4.3/jquery.min.js"></script>--%>
    <%--<script type="text/javascript" src="mintor/model/threeJs/dat.gui.min.js"></script>--%>


    <script type="text/javascript" src="mintor/model/webvr/es6-promise.min.js"></script>
    <script type="text/javascript" src="mintor/model/webvr/three.min.js"></script>
    <script type="text/javascript" src="mintor/model/webvr/VRControls.js"></script>
    <script type="text/javascript" src="mintor/model/webvr/VREffect.js"></script>
    <script type="text/javascript" src="mintor/model/webvr/webvr-polyfill.min.js"></script>
    <script type="text/javascript" src="mintor/model/webvr/webvr-manager.js"></script>
    <script type="text/javascript" src="mintor/model/webvr/VRMLLoader.js"></script>


    <style>
        body {
            width: 100%;
            height: 100%;
            background-color: #000;
            color: #fff;
            margin: 0px;
            padding: 0;
            overflow: hidden;
        }
    </style>

</head>

<body>

<script>

    var container = document.createElement('div');
    document.body.appendChild(container);

    // Setup three.js WebGL renderer. Note: Antialiasing is a big performance hit.
    // Only enable it if you actually need to.
    var renderer = new THREE.WebGLRenderer({antialias: true});
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setClearColor(0xaaaaff, 1.0);                            // 设置canvas背景色(clearColor)
    renderer.setSize(window.innerWidth, window.innerHeight);     // 指定渲染的宽高
    renderer.shadowMapEnabled = true;

    // Create a three.js scene.
    var scene = new THREE.Scene();

    // Create a three.js camera.
    var camera;
    camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.01, 1e10);
    camera.position.set(0, 0, 0);
    scene.add(camera);

    // Apply VR headset positional data to camera.
    var controls = new THREE.VRControls(camera);
    //站立姿态
    controls.standing = true;
    var dirLight = new THREE.DirectionalLight(0xffffff);  //方向光
    dirLight.position.set(130, 150, 1000).normalize();
    camera.add(dirLight);
    camera.add(dirLight.target);

    // Apply VR stereo rendering to renderer.
    var effect = new THREE.VREffect(renderer);
    effect.setSize(window.innerWidth, window.innerHeight);

    // Create a VR manager helper to enter and exit VR mode.
    //按钮和全屏模式管理
    var params = {
        hideButton: false, // Default: false.
        isUndistorted: false // Default: false.
    };
    var manager = new WebVRManager(renderer,effect,params);

    var xaxismotion,yaxismotion,zaxismotion;
    var machineMotion;                              // 机床动作组
    var maxisGroup = undefined;                     // 主轴动作组
    var maxisBase={x:0,y:0,z:0};                    // 主轴基准坐标
    var maxisDeviation={x:0,y:0,z:0};               // 主轴初始化后偏移
    var axisBase={x:0,y:0,z:0};                     // 三轴基准坐标
    var axisOrigin={x:0,y:0,z:0};                   // 三轴原始坐标
    var maxisOrigin={x:0,y:0,z:0};                  // 主轴原始坐标

    var objLoader = new THREE.VRMLLoader();
    objLoader.load('mintor/model/model.wrl', function (geometry) {
        xaxismotion = new Array(geometry.children[0].children[3]);                  // X轴运动块数组
        yaxismotion = new Array(geometry.children[0].children[3].children[5]);      // Y轴运动块数组
        zaxismotion = new Array(                                                    // Z轴运动块数组
            geometry.children[0].children[3].children[5].children[2],
            geometry.children[0].children[3].children[5].children[3],
            geometry.children[0].children[3].children[5].children[4],
            geometry.children[0].children[3].children[5].children[5],
            geometry.children[0].children[3].children[5].children[6]
        );
        machineMotion = new Array(xaxismotion,yaxismotion,zaxismotion);          // 机床运动块数组
        var maxis = geometry.children[0].children[3].children[5].children[6].children[7];
        geometry.rotateY(Math.PI/2);
        maxis.rotateY(-Math.PI/2);

        scene.add(geometry);
        container.appendChild(renderer.domElement);

        maxisGroup = new THREE.Group();                                      // 新建物体组
        var box1 = new THREE.Box3().setFromObject(maxis);                   // 边界框
        maxisGroup.add(maxis);                                              // 将目标块加入组中
        box1.getCenter(maxis.position);                                      // 设置盒子中心
        maxis.position.multiplyScalar(-1);                                   // 反方向移动
        box1.getCenter(maxisGroup.position);
        scene.add(maxisGroup);

        geometry.position.set(0, 0, -3);
        maxisGroup.position.z+=-3;


        maxisOrigin.x=maxisGroup.position.x;                            // 获取主轴原始坐标
        maxisOrigin.y=maxisGroup.position.y;
        maxisOrigin.z=maxisGroup.position.z;
        maxisBase.x=0;maxisBase.y=maxisOrigin.y;maxisBase.z=maxisOrigin.z+0.5;  // 计算基准坐标
        maxisGroup.position.set(maxisBase.x,maxisBase.y,maxisBase.z);        // 把主轴放到基准坐标
        maxisDeviation.x=maxisBase.x-maxisOrigin.x;                          // 计算主轴偏移
        maxisDeviation.y=maxisBase.y-maxisOrigin.y;
        maxisDeviation.z=maxisBase.z-maxisOrigin.z;
                                                                            // 旋转了90度,x<=y块,y<=z块,z<=x块
        axisBase.z=machineMotion[0][0].position.x-maxisDeviation.z;     // 计算三轴初始化后基准坐标
        axisBase.y=machineMotion[2][0].position.y+maxisDeviation.y;
        axisBase.x=machineMotion[1][0].position.z+maxisDeviation.x;
        initAllAxisGroup();                                                 // 把三轴的块移到基准零点
//        for(var iTem in machineMotion[1]){
//            machineMotion[1][iTem].position.z+=axisBase.x;
//        }

    });

    // Kick off animation loop
    requestAnimationFrame(animate);

    window.addEventListener('resize', onResize, true);
    window.addEventListener('vrdisplaypresentchange', onResize, true);
    // Request animation frame loop function

    function animate(timestamp) {
        if (maxisGroup != undefined) {
            rotatyMaxisGroupPosition(0.5);
        }
        // Update VR headset position and apply to camera.
        //更新获取HMD的信息
        controls.update();

        // Render the scene through the manager.
        //进行camera更新和场景绘制
        manager.render(scene, camera, timestamp);

        requestAnimationFrame(animate);
    }

    function onResize(e) {
        effect.setSize(window.innerWidth, window.innerHeight);
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
    }
    function rotatyMaxisGroupPosition(m_speed) {                //  参数为旋转速度
        maxisGroup.rotateY(m_speed*-1.0);                       // 主轴旋转动作
    }
    function initAxisGrouptoPosition(tempGroup,taxis,pos) {
        for(var iTem in tempGroup){
            switch(taxis){
                case 0:tempGroup[iTem].position.x=pos; break;           // x轴移动到目的位置
                case 1:tempGroup[iTem].position.z=pos; break;           // y轴移动到目的位置
                case 2:tempGroup[iTem].position.y=pos; break;           // z轴移动到目的位置
                default:break;
            }
        }
    }
    function initAllAxisGroup() {                                       // 机床三轴根据主轴偏移初始化函数
        initAxisGrouptoPosition(machineMotion[0],0,axisBase.z);
        initAxisGrouptoPosition(machineMotion[1],1,axisBase.x);
        initAxisGrouptoPosition(machineMotion[2],2,axisBase.y);
    }

</script>

</body>
</html>
